<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">


      <a-form-item class="smart-query-form-item" label="仓储区名称">
        <a-input v-model:value="queryForm.storageName" placeholder="请输入仓储区名称" style="width: 160px"/>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="add()">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增仓储区
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :scroll="{ x: 1300 }"
        bordered
        rowKey="enterpriseId"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'icon'">
          <a-image
              :src="text"
              :width="80"
          />
        </template>

        <template v-if="column.dataIndex === 'status'">
          <span :style="{color: text===1?'#87d068':'#f50'}">{{ text === 0 ? '禁用' : '启用' }}</span>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="update(record)">编辑</a-button>
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>

  <!--  添加和修改对话框-->
  <a-modal :title="`${formData.id?'编辑':'新增'}仓储区`" :visible="modalVisible" @cancel="onClose" @ok="save">
    <a-form ref="formRef" :label-col="labelCol" :model="formData" :rules="rules" :wrapper-col="wrapperCol">
      <a-form-item label="仓储区名称" name="storageName">
        <a-input v-model:value="formData.storageName" placeholder="请输入仓储区名称"/>
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea v-model:value="formData.bak" :maxlength="100" placeholder="请输入备注" show-count/>
      </a-form-item>
    </a-form>
  </a-modal>


</template>


<script setup>
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import {useRouter} from 'vue-router';
import _ from "lodash";
import {storageAreaApi} from "/src/views/business/storage/storage-area";


const router = useRouter();

const columns = ref([
  {
    align: 'center',
    title: '仓储区id',
    dataIndex: 'id',
    width: 60,
  },
  {
    align: 'center',
    title: '仓储区名称',
    dataIndex: 'storageName',
    width: 100,
  },
  {
    align: 'center',
    title: '货架数量',
    dataIndex: 'rackNum',
    width: 80,
  },
  {
    align: 'center',
    title: '机器数量',
    dataIndex: 'modelNum',
    width: 80,
  },
  {
    align: 'center',
    title: '备注',
    dataIndex: 'bak',
    width: 80,
  },
  {
    align: 'center',
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 80,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    fixed: 'right'
  },
]);
// 组件ref
const formRef = ref();
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  storageName: [{required: true, message: ''}],
};
let iconImgList = reactive({arr: []});
let quotationImgList = reactive({arr: []});
let modalVisible = ref(false);
const formDataDefault = {
  id: undefined,
  storageName: undefined,
  bak: '',
};

let formData = reactive({...formDataDefault});

const queryFormDataDefault = {
  storageName: undefined,
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();

const quotationTypeOptions = ref([]);

// 重置查询条件
function resetQuery() {
  Object.assign(queryForm, queryFormDataDefault);
  ajaxQuery();
}

onMounted(() => {
  ajaxQuery();
});

function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}
// 查询
async function ajaxQuery() {
  try {
    tableLoading.value = true;
    let responseModel = await storageAreaApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function update(record) {
  modalVisible.value = true;
  Object.assign(formData, record);
}

// 添加
function add() {
  modalVisible.value = true;
}

function iconImgChange(e) {
  console.log(e[0])
  formData.icon = e[0]?.url || '';
}

function quotationImgChange(e) {
  console.log(e[0])
  formData.quotationPhoto = e[0]?.url || '';
}

function onClose() {
  Object.assign(formData, formDataDefault);
  iconImgList.arr = [];
  quotationImgList.arr = [];
  modalVisible.value = false;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

// 保存
async function save() {
  if (!formData.storageName || formData.storageName.trim() === '') {
    return message.error('请输入仓储区名称');
  }
  SmartLoading.show();
  const form = _.cloneDeep(formData)
  try {
    if (form.id) {
      await storageAreaApi.update(form);
    } else {
      await storageAreaApi.add(form);
    }
    message.success(`${form.id ? '修改' : '添加'}成功`);
    ajaxQuery();
    onClose();
  } catch (error) {
    smartSentry.captureError(error);
  } finally {
    SmartLoading.hide();
  }
}

// 删除
function confirmDelete(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.storageName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await storageAreaApi.delete(brandData.id);
    message.success('删除成功');
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

</script>

<style lang="less" scoped>

</style>